package com.zyc.remoting.transport.socket;


import com.zyc.exception.RpcException;
import com.zyc.factory.SingletonFactory;
import com.zyc.registry.ServiceDiscovery;
import com.zyc.registry.zk.ZKServiceDiscoveryImpl;
import com.zyc.remoting.dto.RpcRequest;
import com.zyc.remoting.dto.RpcResponse;
import com.zyc.remoting.transport.RpcRequestTransport;
import lombok.SneakyThrows;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author zyc
 * @create 2022--05--09 10:51
 */
public class SocketRpcClient implements RpcRequestTransport {

    private final ServiceDiscovery serviceDiscovery;

    public SocketRpcClient() {
        serviceDiscovery = SingletonFactory.getInstance(ZKServiceDiscoveryImpl.class);
    }

    @SneakyThrows
    @Override
    public RpcResponse sendRpcRequest(RpcRequest rpcRequest) {
        //通过注册中心查找目标服务地址
        InetSocketAddress inetSocketAddress = serviceDiscovery.lookupService(rpcRequest);
        try (Socket socket = new Socket()) {
            socket.connect(inetSocketAddress);
            //发送请求
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(rpcRequest);
            //接收响应
            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            return (RpcResponse) objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RpcException("服务调用失败:", e);
        }
    }
}
